# coding:utf-8
import re
import sys
import os
import shutil
from itertools import groupby

reg_fn = re.compile(r'^([0-9A-Z]+_[^_]+).+')

FN_G_CACHE = {}


def extract_group_from_fn(fn):
    if fn in FN_G_CACHE:
        return FN_G_CACHE[fn]
    m = reg_fn.search(fn)
    if m:
        group = m.group(1)
        FN_G_CACHE[fn] = group
        return group
    else:
        FN_G_CACHE[fn] = None


def group_move_files(src_folder, des_top_folder):
    all_matching_files = []
    for fn in os.listdir(src_folder):
        if not extract_group_from_fn(fn):
            print(f'{fn} not match pattern')
            continue
        all_matching_files.append(fn)
    for g, fns in groupby(all_matching_files, key=extract_group_from_fn):
        # print(g)
        # print(fns)
        des_folder = os.path.join(des_top_folder, g)
        os.makedirs(des_folder, exist_ok=True)
        for fn in fns:
            src_full = os.path.join(src_folder, fn)
            des_full = os.path.join(des_folder, fn)
            if os.path.isfile(des_full):
                continue
            shutil.move(src_full, des_full)
            print(f'{src_full} --> {des_full}')


if __name__ == "__main__":
    src_folder = r'C:\Users\yang.lei\Downloads\测试文件'
    des_top_folder = r'C:\Users\yang.lei\Downloads\groupedfolder'
    group_move_files(src_folder, des_top_folder)
    print('end of main.')
